package com.gun;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit4.SpringRunner;

import javax.mail.*;

import java.io.IOException;
import java.util.Properties;

/**
 * @author liyupeng
 * @date 2023/9/4&19:20
 * @function TODO:
 * @packageName com.gun
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Receive {

//    @Autowired
//    private MailProperties mailProperties;

    @Test
    public void receiveAndProcessEmail() throws MessagingException, IOException {
        // 创建邮件会话
        // 创建邮件会话
        Properties properties = new Properties();
        properties.setProperty("mail.imap.host", "smtp.qq.com");
        properties.setProperty("mail.imap.port", "587");
//        properties.setProperty("mail.imap.ssl.enable", "true");
        properties.setProperty("mail.imap.ssl.enable", "true"); // 使用TLS协议
        properties.setProperty("mail.smtp.starttls.enable", "true"); // 使用TLS协议
        Session session = Session.getInstance(properties);

        // 连接到邮件服务器
        Store store = session.getStore("imap");
        store.connect("smtp.qq.com", "3280261540@qq.com", "mnrhqqvdazfqdcac");

        // 打开收件箱
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY); // 以只读模式打开收件箱

        // 获取收件箱中的邮件
        Message[] messages = inbox.getMessages();

        // 遍历邮件并解析内容
        // 遍历邮件并解析内容
        for (Message message : messages) {
            String subject = message.getSubject();
            String from = message.getFrom()[0].toString();
            String content = message.getContent().toString();

            // 进一步处理邮件内容，例如打印或保存到数据库
            System.out.println("Subject: " + subject);
            System.out.println("From: " + from);
            System.out.println("Content: " + content);
        }

        // 关闭收件箱和邮件服务器连接
        inbox.close(false);
        store.close();
    }

}
